<?php

$pageName = 'bmo.user'; 

/**
 * Handle file uploads via XMLHttpRequest
 */ 
class User {
    private $user;
    private $sessionOut;
    function __construct($userDaoImpl){  
        $this->userDaoImpl  = $userDaoImpl;
        $this->sessionOut["status"] = 99;
        $this->sessionOut["msg"] = "session time out or phone is not exist!";        
    } 
    
    /**
     * 用户登录
     * @param $phoneNbr
     * @param $md5passwd
     */
    function login($phoneNbr, $md5passwd){
        $rtInfo = "";
    	$userInfo = $this->userDaoImpl->getUserByPhone($phoneNbr);
    	if(empty($userInfo)){
    		$rtInfo["status"]=1;
    		$rtInfo["msg"] ="phone not exist userInfo = {$userInfo}";
    		return $rtInfo;
    	} 
    	$userId = $userInfo["userId"];
    	$passwd = $this->userDaoImpl->getPasswdById($userId);
    	if($passwd == $md5passwd){
        	//TODO 这里的sessionId后面再自动生成
        	$sessionId = "t".date('YmdHis')."u".$userId;
        	$this->userDaoImpl->deprecatedLoginStatus($userId);
			$this->userDaoImpl->saveLoginLog($userId,$sessionId); 
        
	        $rtInfo["status"] = 0;
	        $rtInfo["msg"]="login success";  
        	$obj["sessionId"]= $sessionId;
	        $rtInfo["rt"] = $obj;
        }
        else{        	
	        $rtInfo["status"] = 2;
	        $rtInfo["msg"]="password error!";  
        }
        return $rtInfo;    
    }  
    /**
     * 用户注册
     * @param $phoneNbr
     * @param $md5passwd
     * @param $needCheck
     */
    function register($phoneNbr, $md5passwd,$needCheck=false){
    	$rtInfo = "";
    	$userInfo = $this->userDaoImpl->getUserByPhone($phoneNbr);
    	if($userInfo && $userInfo["userId"]){
    		$rtInfo["status"]=1;
    		$rtInfo["msg"] ="phone number is exist";
    		return $rtInfo;
    	} 
    	$this->userDaoImpl->insertUser($phoneNbr,$needCheck);
    	$userInfo = $this->userDaoImpl->getUserByPhone($phoneNbr);
    	if(!$userInfo || !$userInfo["userId"]){
    		$rtInfo["status"]=2;
    		$rtInfo["msg"] ="create user error!";
    		return $rtInfo;
    	} 
    	$this->userDaoImpl->insertUserPasswd($userInfo["userId"],$md5passwd);
        $rtInfo["status"] = 0;
        $rtInfo["msg"]="register success!"; 
        return $rtInfo;    
    } 
    /**
     * 校验session信息，如果成功获取用户信息，
     * @param $sessionId
     * @return true sesion失效，false如果session存在
     */
	private function isSessionOut($sessionId){
		$this->user = $this->userDaoImpl->queryUserBySession($sessionId);
		if(empty($this->user)){ 
			return true;
		}else{ 
			return false;
		}
	}
    /**
     * 更新用户的地理位置
     * @param $lon
     * @param $lat
     * @param $sessionId
     */
    function updateLocation($lon,$lat,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$userId=$this->user["userId"];
    	$location = $this->userDaoImpl->queryLocationByUserId($userId);
    	if(empty($location)){
    		 $this->userDaoImpl->saveUserLocation($userId,$lon,$lat);
    	}else{
    		 $this->userDaoImpl->updateUserLocation($userId,$lon,$lat);    		
    	}
    	$rt["status"]=0;
    	$rt["msg"]= "update date success!";
    	return $rt;
    }
     
    /**
     * 请求获取指定号码的地理位置
     * @param $phone 查询的电话号码
     * @param $sessionId
     * 
     * @return
     * status 0,返回OK；1，号码不存在；2插入失败，99，session失效
     */
    function requireLoaction($phone,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$rt="";
    	//1.判断请求的号码是否存在
    	$userInfo = $this->userDaoImpl->getUserByPhone($phone);
    	if(empty($userInfo)){
	    	$rt["status"]=1;
	    	$rt["msg"]= "phone[{$phone}] number is not exist !";
	    	return $rt;
    	}
    	//2.如果原来还有请求未处理，就返回原来的id
    	$connArray = array();
    	$connArray["requireUserId"] = $this->user["userId"];
    	$connArray["locatedUserId"] = $userInfo["userId"];
    	$connArray["statusCd"] = '0';//0未处理
    	$coLocationArray = $this->userDaoImpl->queryCoLocation($connArray);
    	if(!empty($coLocationArray) && count($coLocationArray) > 0){
    		$coLocationInfo = $coLocationArray[0];
	    	$rt["status"] = 0;
    		$rt["msg"] = "require success,has been required!";
    		$nbr["nbr"] = $coLocationInfo->id;
    		$rt["rt"] =  $nbr;
	    	return $rt;
    	}
    	
    	//3.生成请求的序列号
    	//$nbr = $this->userDaoImpl->generateNbr();
    	//这里直接插入就好了,通过select LAST_INSERT_ID()这个操作
    	$needCheck = $userInfo["confirm"];
    	$updateUserId = $this->user["userId"];
    	$statusCd = 0;
    	if($needCheck && $needCheck == "N"){
    		 $statusCd = 1;
    		 $updateUserId = -1;
    	} 
    	
    	$this->userDaoImpl->generateRequireLoactionRecord($this->user["userId"],$userInfo["userId"],$updateUserId,$statusCd);
    	$id = $this->userDaoImpl->queryLastInsertId();
    	if($id > 0){
    		$rt["status"] = 0;
    		$rt["msg"] = "require success!";
    		$nbr["nbr"] = $id;
    		$rt["rt"] =  $nbr;
    	}else{    		
    		$rt["status"] = 2;
    		$rt["msg"] = "generate sequire fail!";
    	}
    	//如果不需要校验，直接生成授权流水号
    	if($needCheck && $needCheck == "N"){
    		$this->userDaoImpl->generatePrivilege($id,-1,1);
    	} 
    		
    	return $rt;
    }
    
    /**
     * 回复是否接受请求
     * @param $nbr 发起请求的流水号,这里暂时是相应的id
     * @param $status 1,同意；2，拒绝
     * @param $sessionId
     * 
     * @return
     * 
     */
	function answerRequire($nbr,$status,$sessionId){
		if(!isset($status) || $status != 1 && $status != 2 || empty($nbr)){
			$rt["status"] = 1;
	    	$rt["msg"]= "status [{$status}] ,nbr [{$nbr}] is illegal!";
	    	return $rt;
		}
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$rt="";
    	//1.判断请求的号码是否存在
    	$connArray = array();
    	$connArray["id"] = $nbr;
    	$coLocationArray = $this->userDaoImpl->queryCoLocation($connArray);
    	if(empty($coLocationArray) || count($coLocationArray) == 0){
	    	$rt["status"] = 2;
	    	$rt["msg"]= "[{$nbr}] is not exist !";
	    	return $rt;
    	}
    	$coLocationInfo = $coLocationArray[0];
    	if($coLocationInfo->locatedUserId != $this->user["userId"]){
    		$rt["status"] = 3;
	    	$rt["msg"]= "[you cannot update this status for not the right user ![{$coLocationInfo->locatedUserId} != {$this->user["userId"]}]";
	    	return $rt;
    	}
    	$connArray["statusCd"] = $status;
    	$connArray["updateUserId"] = $this->user["userId"];
    	$this->userDaoImpl->updateCoLocation($nbr,$connArray);
    	
    	if($status == 1){
    		//同意，将生成相应的授权记录信息
    		$this->userDaoImpl->generatePrivilege($nbr,$this->user["userId"],1);
    	}
    	$rt["status"] = 0;
    	$rt["msg"] = "update success!";
    	return $rt;
    }
    
    /**
     * 查询请求的流水号状态
     * @param $nbr
     * @param $sessionId
     */
    function queryRequireLoctionStatus($nbr,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$rt = "";
    	$connArray = array();
    	$connArray["id"] = $nbr;
    	$coLocationArray = $this->userDaoImpl->queryCoLocation($connArray);
    	if(empty($coLocationArray) || count($coLocationArray) == 0){
	    	$rt["status"] = 11;
	    	$rt["msg"]= "[{$nbr}] is not exist !";
	    	return $rt;
    	}
    	$coLocationInfo = $coLocationArray[0];
    	if($coLocationInfo->requireUserId != $this->user["userId"]){
	    	$rt["status"] = 12;
	    	$rt["msg"]= "user info is not match !";
	    	return $rt;
    	}
    	if($coLocationInfo->statusCd == 1){
    		//用户已经同意请求,就同时获取序列号
    		$cond = array();
    		$cond["recordId"] = $nbr;
	    	$rtArray = $this->userDaoImpl->queryCoPrivilege($cond);
	    	if(empty($rtArray) || count($rtArray) == 0 || empty($rtArray[0]->recordId)){ 
		    	$rt["status"] = 13;
		    	$rt["msg"]= " privilege nbr is not created, please contract to the adminstrator!!"; 
	    	}
	    	else{	    		
		    	$rt["status"] = 1;
		    	$rt["msg"]= " OK,please check the privilege nbr!"; 
		    	$privilegeNbr["privilegeNbr"] = $rtArray[0]->id;
		    	$rt["rt"] = $privilegeNbr;
	    	}
	    	
    	}else if($coLocationInfo->statusCd == 2){ 
	    	$rt["status"] = 2;
	    	$rt["msg"]= " well, you have been rejected!"; 
    	}else{    		
	    	$rt["status"] = 3;
	    	$rt["msg"]= " unknow status, please wait {$coLocationInfo->statusCd}!"; 
    	}
    	return $rt;
    }
    /**
     * 查询当前用户被定位的情况
     * 读取成功后，就把状态改成3,已读取
     * @param $sessionId
     */
    function queryRequiredLocatedInfo($sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$rt = "";
	    $rt["status"] = 0;
    	$connArray = array();
    	$connArray["locatedUserId"] = $this->user["userId"];
    	$connArray["statusCd"] = 0;//未处理的状态
    	$coLocationArray = $this->userDaoImpl->queryCoLocationExtr($connArray);
    	$newValsArray = array();  
    	if(empty($coLocationArray) || count($coLocationArray) == 0){
	    	$rt["msg"]= " there is no require to your location."; 
    	}else{
    		$updateInfo = array();
	    	$updateInfo["statusCd"] = 3;
	    	$updateInfo["updateUserId"] = $this->user["userId"];
	    	foreach($coLocationArray as $coLoaction){
	    		$temp = new stdClass ;
	    		$temp->nbr = $coLoaction->id;
	    		$temp->phoneNbr = $coLoaction->requirePhone;
	    		$temp->createDt = $coLoaction->createDt;
	    		$newValsArray[] = $temp;
	    		$this->userDaoImpl->updateCoLocation($coLoaction->id,$updateInfo);
	    	}
	    	$rt["msg"]= " query success.";
    	}
	    $rt["rt"] = $newValsArray;
	    return $rt;
    }
    /**
     * 获取用户的地理位置
     * @param $privilegeNbr
     * @param $sessionId
     */
    function getReqiureLocation($privilegeNbr,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$locationInfo = $this->userDaoImpl->queryUserLocation($this->user["userId"],$privilegeNbr);
    	$rt = "";
    	if(empty($locationInfo)){
    		$rt["status"] = 2;	
    		$rt["msg"] = " cannot not find suitable location infomation {$privilegeNbr}";	
    	}else{    		
    		$rt["status"] = 0;	
    		$rt["msg"] = " query OK";	
    		$rt["rt"] = $locationInfo;
    	}
    	return $rt;
    }
    /**
     * 更新用户分享的地理位置
     * @param $userId
     * @param $lat
     * @param $lon
     * @param $sessionId
     */
    function shareDefaultLocation($lat,$lon,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	}
    	$userId=$this->user["userId"];
    	$location = $this->userDaoImpl->getDefaultShareLocation($userId);
    	if(empty($location)){
    		 $this->userDaoImpl->saveDefaultShareLocation($userId,$lon,$lat);
    	}else{
    		 $this->userDaoImpl->updateShareLocation($userId,$lon,$lat);    		
    	}
    	$rt["status"]=0;
    	$rt["msg"]= "update share location success!";
    	return $rt;
    }
    /**
     * 获取用户分享的地理位置
     * @param $sessionId
     * @param $shareUserId
     */
	function getDefaultShareLocation($phoneNbr,$sessionId){
    	if($this->isSessionOut($sessionId)){
    		return $this->sessionOut;
    	} 
    	
    	$userInfo = $this->userDaoImpl->getUserByPhone($phoneNbr);
    	if(!$userInfo){
    		$rtInfo["status"]=1;
    		$rtInfo["msg"] ="[".$phoneNbr."] user not exist!";
    		return $rtInfo;
    	} 
    	$shareUserId = $userInfo["userId"];
    	$location = $this->userDaoImpl->getDefaultShareLocation($shareUserId);
    	if(empty($location)){ 
    		$rt["status"] = 2;
    		$rt["msg"]= "no location info from this user. !".$shareUserId;
    	}else{  
    		$rt["status"] = 0;
    		$rt["msg"]= "get location back !".$shareUserId;	
    		$rt["rt"] = $location;
    	}
    	return $rt;
    }
}

 
?>